package cn.monkey.family.server.domain.uc.auth.session;

import cn.monkey.family.data.context.ThreadLocalUserSessionContextHolder;
import cn.monkey.family.data.context.UserSessionContextHolder;
import cn.monkey.family.data.uc.auth.Authorization;
import cn.monkey.family.server.domain.uc.auth.AuthorizationManager;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SessionConfig {

    @Bean
    UserSessionRepository userSessionRepository(CacheManager cacheManager) {
        return new CacheableUserSessionRepository(cacheManager);
    }

    @Bean
    UserSessionContextHolder userSessionContextHolder() {
        return new ThreadLocalUserSessionContextHolder();
    }

    @Bean
    FilterRegistrationBean<UserSessionFilter> userSessionFilter(UserSessionRepository userSessionRepository,
                                                                AuthorizationManager authorizationManager,
                                                                UserSessionContextHolder userSessionContextHolder) {
        FilterRegistrationBean<UserSessionFilter> filterRegistrationBean = new FilterRegistrationBean<>();
        UserSessionFilter userSessionFilter = new UserSessionFilter(key -> {
            Authorization authorization = authorizationManager.decrypt(key);
            if (authorization == null) {
                throw new IllegalArgumentException("invalid key: " + key);
            }
            return userSessionRepository.find(authorization.getUid());
        }, userSessionContextHolder::set, userSessionContextHolder::remove);
        filterRegistrationBean.setFilter(userSessionFilter);
        filterRegistrationBean.setOrder(1);
        return filterRegistrationBean;
    }

}
